package com.example.pm.ending.server.service.impl;

import com.example.pm.ending.server.ex.ServiceException;
import com.example.pm.ending.server.mapper.*;
import com.example.pm.ending.server.module.admin.AddNewAdminEntityDTO;
import com.example.pm.ending.server.module.admin.AdminListEntityVO;
import com.example.pm.ending.server.module.admin.UpdateAdminEntityDTO;
import com.example.pm.ending.server.pojo.entity.*;
import com.example.pm.ending.server.pojo.vo.*;

import com.example.pm.ending.server.service.IAdminModuleService;
import com.example.pm.ending.server.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class AdminModuleServiceImpl implements IAdminModuleService {


    @Autowired
    AdminMapper adminMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    AdminRoleRelMapper adminRoleRelMapper;
    @Autowired
    PublishAdminMapper publishAdminMapper;




    @Override
    public void addNew(AddNewAdminEntityDTO addNewAdminEntityDTO) {
        log.debug("开始处理[添加管理员]业务");
        log.debug("传来的参数为：{}",addNewAdminEntityDTO);
        //判断角色不能为业主（2）
        Long[] roleIds = addNewAdminEntityDTO.getRoleIds();
        Long rid=0L;
        for (Long roleId : roleIds) {
            if (roleId == 2) {
                // 是：抛出异常
                String message = "添加管理员失败，非法角色访问！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
            rid=roleId;
        }
        //判断手机号是否被使用
        Integer countPhone = adminMapper.countByPhone(addNewAdminEntityDTO.getPhone());
        if (countPhone > 0) {
            String message = "该手机号已经被注册";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        Admin admin = new Admin();
        BeanUtils.copyProperties(addNewAdminEntityDTO,admin);
        admin.setAvatar("https://imgavater.ui.cn/avatar/big.png");
        admin.setEnable(ENABLE_STATE);
        admin.setLoginCount(LONG_COUNT);
        LocalDateTime nowtime = LocalDateTime.now();
        admin.setGmtCreate(nowtime);
        admin.setRoleId(rid);
        log.debug("即将执行插入admin数据，参数：{}", admin);
        adminMapper.insert(admin);

        // 为新添加的管理员分配角色
        // 基于角色ID的数组来创建List<AdminRole>
        List<AdminRoleRel> adminRoleList = new ArrayList<>();
        for (Long roleId : roleIds) {
            AdminRoleRel adminRole = new AdminRoleRel();
            adminRole.setAdminId(admin.getId());
            adminRole.setRoleId(roleId);
            adminRoleList.add(adminRole);
        }
        // 调用AdminRoleMapper对象的insertBatch()执行插入
        int rows = adminRoleRelMapper.insertBatch(adminRoleList);
        if (rows < 1) {
            String message = "添加管理员失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

    }

    @Override
    public List<AdminListEntityVO> list() {
        log.debug("开始处理【查询管理员列表】的业务，参数：无");
        List<AdminListEntityVO> list = adminMapper.list();
        return list;
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据id删除管理员】的业务，参数：{}", id);
        //判断管理员公布表是否发布
        int row=publishAdminMapper.countByAdminId(id);
        if(row>0){
            log.debug("开始处理【根据adminID删除管理员公布表】的业务，参数：{}", id);
            publishAdminMapper.deleteByAdminId(id);
            log.debug("执行删除adminID删除管理员公布表数据，参数：{}", id);
        }
        adminMapper.deleteById(id);
        log.debug("完成处理【根据id删除管理员】的业务，参数：{}", id);
    }

    @Override
    public void updateInfoById(Long id, UpdateAdminEntityDTO updateAdminEntityDTO) {
        log.debug("开始处理[修改管理员]业务");
        log.debug("传来的参数为：{}",updateAdminEntityDTO);

        Long[] roleIds = updateAdminEntityDTO.getRoleIds();
        Long rid=0L;
        for (Long roleId : roleIds) {
            if (roleId == 2) {
                // 是：抛出异常
                String message = "添加管理员失败，非法角色访问！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
            rid=roleId;
        }

        Admin admin = new Admin();
        BeanUtils.copyProperties(updateAdminEntityDTO,admin);
        LocalDateTime nowtime = LocalDateTime.now();
        admin.setGmtModified(nowtime);
        admin.setRoleId(rid);
        //判断手机号是否被使用
        Integer countPhone = adminMapper.countByPhone(admin.getPhone());
        if (countPhone > 1) {
            String message = "该手机号已经被注册";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        log.debug("即将执行插入admin数据，参数：{}", admin);
        admin.setId(updateAdminEntityDTO.getId());
        adminMapper.update(admin);

        AdminRoleRel adminRoleRel=new AdminRoleRel();
        adminRoleRel.setRoleId(rid);
        adminRoleRel.setAdminId(admin.getId());
        adminRoleRel.setGmtModified(nowtime);
        log.debug("即将执行修改admin_role-rel数据，参数：{}", adminRoleRel);
        adminRoleRelMapper.update(adminRoleRel);
    }

    @Override
    public void setEnable(Long id) {
        log.debug("开始处理【启用类别】的业务，参数：{}", id);
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        log.debug("开始处理【禁用类别】的业务，参数：{}", id);
        updateEnableById(id, 0);
    }

    @Override
    public AdminStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询类别详情】的业务，参数：{}", id);
        AdminStandardVO queryResult = adminMapper.getAdminById(id);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "查询类别详情失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        log.debug("xxxxxxxsssss{}",queryResult);
        return queryResult;
    }


    public void updateEnableById(Long id, Integer enable) {
        // 调用Mapper对象的getStandardById()方法执行查询
        AdminStandardVO adminid = adminMapper.getAdminById(id);
        // 判断查询结果是否为null，如果是，则抛出异常
        if (adminid == null) {
            String message = ENABLE_TEXT[enable] + "类别失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        // 判断查询结果中的enable与参数enable是否相同，如果是，则抛出异常（当前状态与目标状态相同，没必要执行更新）
        if (adminid.getEnable() == enable) {
            String message = ENABLE_TEXT[enable] + "类别失败，此类别已经处于" + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        // 创建Category对象
        Admin updateAdmin = new Admin();
        // 向Category对象中封装属性值：id, enable，均来自方法参数
        updateAdmin.setId(id);
        updateAdmin.setEnable(enable);
        // 调用Mapper对象的update()方法执行更新
        int rows = adminMapper.update(updateAdmin);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }




}
